package com.wmx.mp.controller;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wmx.mp.config.MybatisPlusConfig;
import com.wmx.mp.entity.BasUser;
import com.wmx.mp.service.IBasUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户控制层
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2023/3/4 8:54
 */
@RestController
public class BasUserController {
    @Resource
    private IBasUserService basUserService;

    /**
     * 分页查询必须配置分页拦截器才会生效 {@link MybatisPlusConfig}，否则不会分页，而是查询全部。
     * http://localhost:8080/basUser/selectPage?page=1&count=10
     * http://localhost:8080/basUser/selectPage?keyword=Billie
     *
     * @param page  ：当前页，从1开始。
     * @param count ：每页显示条数
     * @return
     */
    @GetMapping("/basUser/selectPage")
    public IPage<BasUser> selectPage(@RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "20") Integer count,
                                     String keyword) {
        IPage<BasUser> allList = basUserService.selectPage(page, count, keyword);
        return allList;
    }

    /**
     * 根据 ID 查询
     * http://localhost:8080/basUser/selectById?id=1
     *
     * @param id ：主键ID
     * @return
     */
    @GetMapping("/basUser/selectById")
    public Map<String, Object> selectById(@RequestParam Integer id) {
        BasUser basUser = basUserService.selectById(id);

        Map<String, Object> build = MapUtil.builder(new HashMap<String, Object>())
                .put("code", "200")
                .put("msg", "查询成功")
                .put("data", basUser).build();
        return build;
    }

    /**
     * 查询（根据ID 批量查询）
     * http://localhost:8080/basUser/selectBatchIds?idStr=1,4,5,7,9
     *
     * @param idStr ：主键ID集合
     * @return
     */
    @GetMapping("/basUser/selectBatchIds")
    public Map<String, Object> selectBatchIds(@RequestParam String idStr) {
        String[] split = idStr.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : split) {
            if (NumberUtil.isInteger(s)) {
                ids.add(Integer.parseInt(s));
            }
        }
        List<BasUser> basUsers = basUserService.selectBatchIds(ids);
        Map<String, Object> build = MapUtil.builder(new HashMap<String, Object>())
                .put("code", "200")
                .put("msg", "查询成功")
                .put("data", basUsers).build();
        return build;
    }

    /**
     * 查询（根据 columnMap 条件）
     * http://localhost:8080/basUser/selectByMap
     * <pre>
     *  {
     *     "email": null,
     *     "user_Id": 4,
     *     "user_Name": "Sandy"
     * }
     * </pre>
     *
     * @param columnMap ：表字段 map 对象，key 对应表中的列名，而不是实体对象的属性名。
     */
    @PostMapping("/basUser/selectByMap")
    public Map<String, Object> selectByMap(@RequestBody Map<String, Object> columnMap) {
        List<BasUser> basUsers = basUserService.selectByMap(columnMap);
        Map<String, Object> build = MapUtil.builder(new HashMap<String, Object>())
                .put("code", "200")
                .put("msg", "查询成功")
                .put("data", basUsers).build();
        return build;
    }

    /**
     * 根据 entity 条件，查询一条记录。
     * http://localhost:8080/basUser/selectOne?id=5
     * 例如 qw.last("limit 1") 限制取一条记录, 注意：如果结果是多条数据，则会报异常：TooManyResultsException
     *
     * @param id ：主键ID
     */
    @GetMapping("/basUser/selectOne")
    public Map<String, Object> selectOne(@RequestParam Integer id) {
        BasUser basUser = basUserService.selectOne(id);
        Map<String, Object> build = MapUtil.builder(new HashMap<String, Object>())
                .put("code", "200")
                .put("msg", "查询成功")
                .put("data", basUser).build();
        return build;
    }

    /**
     * http://localhost:8080/basUser/selectObjs?email=test55@baomidou.com
     *
     * @param email
     * @return
     */
    @GetMapping("/basUser/selectObjs")
    public Map<String, Object> selectObjs(String email) {
        List<Object> objectList = basUserService.selectObjs(email);
        Map<String, Object> build = MapUtil.builder(new HashMap<String, Object>())
                .put("code", 200)
                .put("msg", "查询成功")
                .put("data", objectList).build();
        return build;
    }

    /**
     * 根据 Wrapper 条件，查询总记录数
     * http://localhost:8080/basUser/selectCount
     */
    @GetMapping("/basUser/selectCount")
    public Map<String, Object> selectCount() {
        Long selectCount = basUserService.selectCount();
        Map<String, Object> build = MapUtil.builder(new HashMap<String, Object>())
                .put("code", "200")
                .put("msg", "查询成功")
                .put("data", selectCount).build();
        return build;
    }

    /**
     * 条件构造器 QueryWrapper 查询API
     * http://localhost:8080/basUser/queryWrapper?keyword=Tom
     * http://localhost:8080/basUser/queryWrapper?userId=1
     * http://localhost:8080/basUser/queryWrapper?birthday=1900-01-01
     * http://localhost:8080/basUser/queryWrapper?nameStr=Sandy,Tom,Billie
     *
     * @param keyword
     * @return
     */
    @GetMapping("/basUser/queryWrapper")
    public List<BasUser> queryWrapper(String keyword, Integer userId, String birthday, String nameStr) {
        List<String> names = new ArrayList<>();
        if (StringUtils.isNotBlank(nameStr)) {
            String[] split = nameStr.split(",");
            names.addAll(Arrays.asList(split));
        }
        List<BasUser> allList = basUserService.queryWrapper(keyword, userId, birthday, names);
        return allList;
    }

    /**
     * LambdaQueryWrapper：Lambda 语法使用 Wrapper，使用实体对象属性名自动映射数据库表列名，而不用写死列名。
     * http://localhost:8080/basUser/lambdaQueryWrapper?keyword=Tom
     *
     * @param keyword
     * @param userId
     * @param birthday
     * @param nameStr
     * @return
     */
    @GetMapping("/basUser/lambdaQueryWrapper")
    public List<BasUser> lambdaQueryWrapper(String keyword, Integer userId, String birthday, String nameStr) {
        List<String> names = new ArrayList<>();
        if (StringUtils.isNotBlank(nameStr)) {
            String[] split = nameStr.split(",");
            names.addAll(Arrays.asList(split));
        }
        List<BasUser> allList = basUserService.lambdaQueryWrapper(keyword, userId, birthday, names);
        return allList;
    }

    /**
     * 查询表中一共有多少条数据
     * http://localhost:8080/basUser/countAll
     *
     * @return
     */
    @GetMapping("/basUser/countAll")
    public Map<String, Object> countAll() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", 200);
        dataMap.put("message", "操作成功");
        int countAll = basUserService.countAll();
        dataMap.put("data", countAll);
        return dataMap;
    }

    /**
     * 批量新增保存。
     * 插入操作时：如果属性没有指定，或者指定值为null，则属性名称不会出现在 insert into sql中。
     * http://localhost:8080/basUser/saveList
     * <pre>
     *     [
     *     {
     *         "birthday": "1993-02-11 00:00:00",
     *         "email": "test54@wangmaoxiong.com",
     *         "userName": "李世民"
     *     },
     *     {
     *         "birthday": "1997-04-15 00:00:00",
     *         "email": "test55@baomidou.com",
     *         "userId": 55,
     *         "userName": "李元吉"
     *     }
     * ]
     * </pre>
     *
     * @param basUserList ：待新增保存的数据
     * @return
     */
    @PostMapping("/basUser/saveList")
    public Map<String, String> saveList(@RequestBody List<BasUser> basUserList) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        if (basUserList == null || basUserList.isEmpty()) {
            return resultMap;
        }
        basUserList.stream().forEach(item -> {
            item.setIsDelete(2);
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
        });
        basUserService.insertList(basUserList);
        return resultMap;
    }

    /**
     * 批量更新保存
     * http://localhost:8080/basUser/updateList
     *
     * <pre>
     *   [
     *     {
     *         "email": "test1@wangmaoxiong.com",
     *         "isDelete": 2,
     *         "userId": 1,
     *         "userName": "Jone Wang"
     *     },
     *     {
     *         "birthday": "1994-09-21 00:00:00",
     *         "createTime": "2023-03-04 10:00:00",
     *         "email": null,
     *         "userId": 2,
     *         "userName": "Jack Li"
     *     }
     * ]
     * </pre>
     *
     * @param basUserList ：待更新保存的数据
     * @return
     */
    @PostMapping("/basUser/updateList")
    public Map<String, String> updateList(@RequestBody List<BasUser> basUserList) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        if (basUserList == null || basUserList.isEmpty()) {
            return resultMap;
        }
        basUserList.stream().forEach(item -> item.setUpdateTime(new Date()));
        basUserService.updateById(basUserList);
        return resultMap;
    }

    /**
     * 根据 whereEntity 条件，更新记录
     * http://localhost:8080/basUser/update
     * <pre>
     * {
     *     "birthday": "1995-06-05 00:00:00",
     *     "email": "test31@baomidou.com",
     *     "isDelete": 2,
     *     "updateTime": "2023-03-05 10:00:00",
     *     "userId": 3,
     *     "userName": "Tom2"
     * }
     * </pre>
     *
     * @param basUser
     * @return
     */
    @PostMapping("/basUser/update")
    public Map<String, String> update(@RequestBody BasUser basUser) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        basUserService.update(basUser);
        return resultMap;
    }

    /**
     * 批量删除保存
     * http://localhost:8080/basUser/deleteList
     *
     * <pre>
     *   [
     *        {
     * 		"userId": 1,
     * 		"userName": "Jone Wang",
     * 		"email": "test1@wangmaoxiong.com",
     * 		"birthday": "1993-08-11 00:00:00",
     * 		"createTime": "2023-03-04 10:00:00",
     * 		"updateTime": "2023-03-05 10:00:00",
     * 		"isDelete": 2
     *    },
     *    {
     * 		"userId": 2,
     * 		"userName": "Jack Li",
     * 		"email": "test2@wangmaoxiong.com",
     * 		"birthday": "1994-09-21 00:00:00",
     * 		"createTime": "2023-03-04 10:00:00",
     * 		"updateTime": "2023-03-05 10:00:00",
     * 		"isDelete": 2
     *    }
     * ]
     * </pre>
     *
     * @param basUserList ：待删除的数据
     * @return
     */
    @PostMapping("/basUser/deleteList")
    public Map<String, String> deleteList(@RequestBody List<BasUser> basUserList) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        if (basUserList == null || basUserList.isEmpty()) {
            return resultMap;
        }
        basUserList.stream().forEach(item -> item.setUpdateTime(new Date()));
        basUserService.deleteBatchIds(basUserList);
        return resultMap;
    }

    /**
     * 根据主键 ID 删除。
     * http://localhost:8080/basUser/deleteById?id=1
     *
     * @param id 主键ID
     */
    @GetMapping("/basUser/deleteById")
    public Map<String, String> deleteById(@RequestParam Integer id) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        basUserService.deleteById(id);
        return resultMap;
    }

    /**
     * 根据实体(ID)删除.
     * http://localhost:8080/basUser/deleteById2
     * <pre>
     *     {
     *     "birthday": "1995-03-05 00:00:00",
     *     "createTime": "2023-03-04 10:00:00",
     *     "email": "test8@wangmaoxiong.com",
     *     "isDelete": 2,
     *     "updateTime": "2023-03-05 10:00:00",
     *     "userId": 8,
     *     "userName": "宋远桥"
     * }
     *
     * @param basUser ：实体对象
     * @return
     */
    @PostMapping("/basUser/deleteById2")
    public Map<String, String> deleteById2(@RequestBody BasUser basUser) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        basUserService.deleteById(basUser);
        return resultMap;
    }

    /**
     * 根据 columnMap 条件，删除记录.
     * http://localhost:8080/basUser/deleteByMap
     *
     * @param columnMap: 表字段 map 对象，key是表中的列名，而不是实体对象的属性名。
     *                   <p>
     *                   {
     *                   "email": "test11@wangmaoxiong.com",
     *                   "user_Id": 11,
     *                   "user_Name": "张无忌"
     *                   }
     *                   </p>
     * @return
     */
    @PostMapping("/basUser/deleteByMap")
    public Map<String, String> deleteByMap(@RequestBody Map<String, Object> columnMap) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        basUserService.deleteByMap(columnMap);
        return resultMap;
    }

    /**
     * 根据 entity 条件，删除记录.
     * <pre>
     * http://localhost:8080/basUser/deleteByQuery?email=test7@wangmaoxiong.com
     * </pre>
     * int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper)
     * * @param queryWrapper 实体对象封装操作类（可以为 null,里面的 entity 用于生成 where 语句）
     */
    @GetMapping("/basUser/deleteByQuery")
    public Map<String, String> deleteByQuery(@RequestParam String email) {
        Map<String, String> resultMap = MapUtil.builder("code", "200").put("msg", "操作成功").build();
        basUserService.deleteByQuery(email);
        return resultMap;
    }
}
